package cn.biao.epic.sys.core.auth.filter;

import cn.biao.epic.base.auth.jwt.JwtTokenUtil;
import cn.biao.epic.core.util.ToolUtil;
import cn.biao.epic.sys.core.auth.cache.SessionManager;
import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Optional;

import static cn.biao.epic.base.consts.ConstantsContext.getTokenHeaderName;

/**
 * @Auther Uncle_Z
 * @date 2019/12/16 13:51
 * @Email:2545375@qq.com
 * @Descrition
 */
@Component
public class JwtAuthorizationFilter extends OncePerRequestFilter {

    @Autowired
    private SessionManager sessionManager;

    public JwtAuthorizationFilter(){};

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {
        String[] regs = {"/assets/**", "/favicon.ico", "/activiti-editor/**"};
        for(String reg: regs){
            if (new AntPathMatcher().match(reg,httpServletRequest.getServletPath())){
                filterChain.doFilter(httpServletRequest,httpServletResponse);
                return;
            }
        }

        String tokenHeader = getTokenHeaderName();
        final String requestHeader = httpServletRequest.getHeader(tokenHeader);

        String username = null;
        String authToken = null;

        // 1.从cookie中获取token
        Cookie[] cookies = httpServletRequest.getCookies();
        if (cookies != null) {
            Optional<String> token =  Arrays.stream(cookies).map(Cookie::getName)
                    .filter(v -> StrUtil.equals(v, tokenHeader))
                    .findAny();
            authToken = token.orElse("");
        }

        // 2.如果cookie中没有token，则从header中获取token
        if (ToolUtil.isEmpty(authToken)) {
            if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
                authToken = requestHeader.substring(7);
            }
        }

        //通过token获取用户名
        if (ToolUtil.isNotEmpty(authToken)) {
            try {
                username = JwtTokenUtil.getJwtPayLoad(authToken).getAccount();
            } catch (IllegalArgumentException | JwtException e) {
                //请求token为空或者token不正确，忽略，并不是所有接口都要鉴权
            }
        }

        //如果帐号不为空 并且没有设置security上下文 则设置上下文
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = sessionManager.getSession(authToken);
            if (userDetails == null) {
                Cookie[] tempCookie = httpServletRequest.getCookies();
                for (Cookie cookie : tempCookie) {
                    if (StrUtil.equals(tokenHeader,cookie.getName())) {
                        Cookie temp = new Cookie(cookie.getName(),"");
                        temp.setMaxAge(0);
                        httpServletResponse.addCookie(temp);
                    }
                }

                httpServletResponse.setStatus(401);
                return;
            }
            UsernamePasswordAuthenticationToken authenticationToken = new
                    UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
